package hu.debrecen.adastra.card.service;

import hu.debrecen.adastra.card.repository.AccountRepository;
import hu.debrecen.adastra.card.repository.UserConnectionRepository;
import hu.debrecen.adastra.card.repository.domain.Account;
import hu.debrecen.adastra.card.repository.domain.BotAccount;
import hu.debrecen.adastra.card.repository.domain.social.UserConnection;
import hu.debrecen.adastra.card.web.domain.UserSocialReference;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;

public class SocialUserService {

	private static final Logger LOGGER = LoggerFactory.getLogger(SocialUserService.class);

	private final AccountRepository accountRepository;

	private final UserConnectionRepository userConnectionRepository;

	@Inject
	public SocialUserService(final AccountRepository accountRepository, final UserConnectionRepository userConnectionRepository) {
		this.accountRepository = accountRepository;
		this.userConnectionRepository = userConnectionRepository;
	}

	@Cacheable(value = "userSocialReferences", key = "#account.username")
	public UserSocialReference getUserSocialReference(final Account account) {

		if (account instanceof BotAccount) {
			return new UserSocialReference(account.getUsername(), account.getUsername(), account.getFirstName(), account.getLastName(), account.getType());
		}

		UserConnection userConnection = this.userConnectionRepository.getUserConnectionByUserId(account.getUsername());
		UserSocialReference userSocialReference = new UserSocialReference(userConnection.getConnectionPK().providerUserId, account.getUsername(), account.getFirstName(), account.getLastName(),
				account.getType());

		SocialUserService.LOGGER.debug("UserSocialReference: {}", userSocialReference);
		return userSocialReference;
	}

	@Cacheable(value = "accounts", key = "#username")
	public Account getAccount(final String username) {
		return this.accountRepository.findAccountByUsername(username);
	}

}
